<template>
  <div class="header_main">
    <div style="font-size: 20px">
      <el-icon v-if="expand" @click="changeStatus()"><DArrowRight /></el-icon>
      <el-icon v-else @click="changeStatus()"><DArrowLeft /></el-icon>
    </div>
    <h1>欢迎使用博客系统</h1>
    <div style="font: 18px">
      <el-dropdown style="font-size: 18px">
        <span class="el-dropdown-link">
          {{ username }}
          <el-icon class="el-icon--right">
            <arrow-down />
          </el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item divided @click="changeNameVisible = true"
              >修改用户名</el-dropdown-item
            >
            <el-dropdown-item divided @click="changePwdVisible = true"
              >修改密码</el-dropdown-item
            >
            <el-dropdown-item divided @click="logout()"
              >退出登录</el-dropdown-item
            >
            <el-dropdown-item divided @click="handleDeleteUser()"
              >注销账户</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <el-dialog
      v-model="changeNameVisible"
      title="修改用户名"
      center
      width="35%"
    >
      <el-form>
        <el-form-item label="新用户名：">
          <el-input v-model="newUserData.username" clearable />
        </el-form-item>
        <div style="display: flex; justify-content: center">
          <el-button type="success" @click="changeName">确认</el-button>
          <el-button type="primary" @click="cancelChange(changeNameVisible)"
            >取消</el-button
          >
        </div>
      </el-form>
    </el-dialog>

    <!-- 注意这里要用v-model，不能用v-show-->
    <el-dialog v-model="changePwdVisible" title="修改密码" center width="40%">
      <el-form :label-position="labelPosition" label-width="auto">
        <el-form-item label="原始密码：">
          <el-input type="password" v-model="newUserData.oldPwd" clearable />
        </el-form-item>
        <el-form-item label="新密码：">
          <el-input type="password" v-model="newUserData.newPwd" clearable />
        </el-form-item>
        <el-form-item label="确认密码：">
          <el-input type="password" v-model="verPwd" clearable />
        </el-form-item>
        <div style="display: flex; justify-content: center">
          <el-button type="success" @click="changePwd">确认</el-button>
          <el-button type="primary" @click="cancelChange(changePwdVisible)"
            >取消</el-button
          >
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { changeInfo, deleteUser } from "@/api/user.js";
import { useMenuStore } from "@/stores/menu.js";
import { storeToRefs } from "pinia";
import { useUserStore } from "@/stores/user.js";
import { ref } from "vue";
import router from "@/router";

const menuStore = useMenuStore();
const userStore = useUserStore();
let { userId, username } = storeToRefs(userStore);
let { expand } = storeToRefs(menuStore);
let changeNameVisible = ref(false);
let changePwdVisible = ref(false);
let newUserData = ref({
  id: userId.value,
  username: username.value,
  oldPwd: "",
  password: "",
});
let verPwd = ref("");

function changeStatus() {
  expand.value = !expand.value;
  menuStore.setExpand(expand.value);
}

function changeName() {
  changeInfo(newUserData.value)
    .then((response) => {
      let res = response.data;
      if (res.code == 200) {
        console.log(newUserData.value.username);
        ElMessage.success(res.message);
        // 不管是否修改名字，都可以赋值，不修改赋值为原有名字
        userStore.setUserInfo(userId.value, newUserData.value.username);
      }
    })
    .catch(() => {
      // 修改失败恢复原有用户名
      newUserData.value.username = username.value;
    });
  changeNameVisible.value = false;
}

function cancelChange() {
  if (changeNameVisible.value) changeNameVisible.value = false;
  else if (changePwdVisible.value) changePwdVisible.value = false;
  newUserData.value.username = username.value;
  newUserData.value.oldPwd = "";
  newUserData.value.newPwd = "";
  verPwd.value = "";
}

function changePwd() {
  if (newUserData.value.newPwd == "") {
    ElMessage.error("新密码不能为空");
  } else if (newUserData.value.newPwd != verPwd.value) {
    ElMessage.error("确认密码不一致");
  } else {
    newUserData.value.username = "";
    // 校验密码是否合理放到后端，如果成功直接修改密码，否则返回错误信息
    changeInfo(newUserData.value)
      .then((response) => {
        let res = response.data;
        if (res.code == 200) {
          ElMessage.success(res.message);
          userStore.setUserInfo(undefined, undefined);
          router.push("/login");
          changePwdVisible.value = false;
        }
      })
      .catch(() => {
        newUserData.value.oldPwd = "";
        newUserData.value.newPwd = "";
        verPwd.value = "";
      });
  }
}

function logout() {
  ElMessageBox.confirm("确认要退出登录吗", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      ElMessage({
        type: "success",
        message: "退出成功",
      });
      userStore.setUserInfo(undefined, undefined);
      router.push("/login");
    })
    .catch(() => {});
}

function handleDeleteUser() {
  ElMessageBox.confirm("确认要注销该用户吗", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "error",
  })
    .then(() => {
      console.log(userId.value);
      deleteUser(userId.value).then((response) => {
        let res = response.data;
        if (res.code == 200) {
          ElMessage({
            type: "success",
            message: "注销用户成功",
          });
          userStore.setUserInfo(undefined, undefined);
          router.push("/login");
        }
      });
    })
    .catch(() => {});
}
</script>

<style lang="scss" scoped>
.header_main {
  /* 三个div元素在同一行*/
  display: flex;
  justify-content: space-between;
  /* 上下居中 */
  align-items: center;
}
/* el-dropdown去除黑框*/
:deep(.el-tooltip__trigger:focus-visible) {
  outline: unset;
}
/* el-dialog中内容居中*/
:deep(.el-dialog__body) {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
